//
//  UseTimeViewController.swift
//  EasePods
//
//  Created by 李然 on 2024/5/30.
//

import UIKit
import EarbudsCommon
import JXSegmentedView

class UseTimeViewController: ViewController {
    
    var dataSource: [TimeRangeType] {
        return self.segmentView.dataSource
    }
    
    var date = Date()
    
    override func makeUI() {
        super.makeUI()
        
        self.navigation.item.title = R.string.localizable.use_time_title()
        self.navigation.bar.backgroundColor = .clear
        self.view.backgroundColor = R.color.common_10_bg_page()
        
        let calendarButton = Button(type: .custom)
        calendarButton.setImage(R.image.ic_use_time_date(), for: .normal)
        calendarButton.rx.tap.subscribe(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            let calendarView = CalendarView(calendarType: .useTime, defaultDate: self.date)
            calendarView.selectDate = { [weak self] date in
                self?.date = date
                self?.listContainerView.reloadData()
            }
            calendarView.addTo(nil)
        }).disposed(by: rx.disposeBag)
        self.navigation.item.rightBarButtonItem = BarButtonItem(customView: calendarButton)
        
        view.addSubview(segmentView)
        segmentView.snp.makeConstraints { make in
            make.top.equalTo(kNavHeight + 20)
            make.leading.equalTo(20)
            make.trailing.equalTo(-20)
            make.height.equalTo(36)
        }
        
        view.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.top.equalTo(segmentView.snp.bottom).offset(4)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    lazy var segmentView: UseTimeDateSegmentView = {
        let view = UseTimeDateSegmentView()
        view.segmentedView.listContainer = self.listContainerView
        return view
    }()
    
    lazy var listContainerView: JXSegmentedListContainerView! = {
        return JXSegmentedListContainerView(dataSource: self)
    }()

}

extension UseTimeViewController: JXSegmentedListContainerViewDataSource  {
    
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        self.dataSource.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        let type = self.dataSource[index]
        let vc = UseTimeDetailViewController(timeRangeType: type, date: date)
        return vc
    }
}
